<template>
  <div class="center">
    <div v-if="resData && resData.length > 0" class="report-content">
      <div class="report-main">
        <div class="report-item" v-for="item in resData" :key="item.id">
          <div class="report-title">{{ item.title }}</div>
          <div class="file-type">文件类型：{{ item.fileType }}</div>
          <div class="report-time">创建时间：{{ item.createTime }}</div>
          <div class="report-person">创建人：{{ item.createPerson }}</div>
          <div class="report-dispose">
            <el-button type="primary" size="small" @click="readFile(item.fileName, item.fileType)"
              >预览</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="downloadFile(item.fileName, item.fileType)"
              >下载</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <div v-else class="no-data">暂无数据</div>
    <el-dialog v-model="open" :before-close="() => (open = false)" width="950">
      <vue-office-docx
        v-if="data.download.docx"
        :src="data.download.docx"
        class="preview"
        style="height: 350px"
        @rendered="rendered"
      />
      <vue-office-excel
        v-if="data.download.excel"
        :src="data.download.excel"
        class="preview"
        style="height: 350px"
        @rendered="rendered"
      />
      <vue-office-pdf
        v-if="data.download.pdf"
        :src="data.download.pdf"
        class="preview"
        style="height: 350px"
        @rendered="rendered"
        @error="errorHandler"
      />
      <div class="view-text" v-if="data.download.other">{{ data.download.txt }}</div>
      <div v-if="data.download.md" class="view-md" v-html="markdownContent"></div>
      <img v-if="data.download.image" :src="data.download.image" class="view-image" />
      <iframe
        v-if="data.download.pptx"
        :src="`/PPTXjs/index.html?file=` + data.download.pptx"
        width="100%"
        height="300"
        frameborder="0"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { download, downloadTxt, getFileList } from '@/api/download'
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'
//引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel'
//引入相关样式
import '@vue-office/excel/lib/index.css'
//引入VueOfficePdf组件
import VueOfficePdf from '@vue-office/pdf'
// 显示markdown文件
import { marked } from 'marked'
const obj = {
  docx: '',
  excel: '',
  pdf: '',
  image: '',
  pptx: '',
  md: '',
  other: ''
}
const copyObj = JSON.parse(JSON.stringify(obj))
const data = reactive({
  download: {
    ...copyObj
  }
})

onMounted(() => {
  initData()
})
const open = ref(false)
// 获取文件列表
const resData = ref([])
const markdownContent = ref('')
async function initData() {
  try {
    resData.value = await getFileList()
  } catch (error) {
    throw new Error(error, '没连接服务器')
  }
}
const readFile = async (fileName, fileType) => {
  let res = null
  let url = null
  if (['txt', 'md'].indexOf(fileType) == '-1') {
    res = await download({
      fileName,
      fileType
    })
    // 创建一个URL链接以供下载或预览
    url = window.URL.createObjectURL(res)
  } else {
    res = await downloadTxt({
      fileName,
      fileType
    })
    url = res
  }

  data.download = {
    ...copyObj
  }
  const markdownRM = new marked.Renderer()
  switch (fileType) {
    case 'xlsx':
      data.download.excel = url
      break
    case 'docx':
      data.download.docx = url
      break
    case 'pdf':
      data.download.pdf = url
      break
    case 'txt':
      data.download.other = url
      break
    case 'png':
    case 'jpg':
      data.download.image = url
      break
    case 'pptx':
      data.download.pptx = url
      break
    case 'md':
      data.download.md = url
      marked.setOptions({
        renderer: markdownRM, // 一个对象，包含用于将标记呈现为 HTML 的函数
        pedantic: false, // 如果为真，则尽可能符合原文。不要修复原始的 Markdown 错误或行为。关闭并覆盖
        gfm: true, // 如果为 true，请使用已批准的 GitHub Flavored Markdown （GFM） 规范
        tables: true,
        breaks: false, // 如果为 true，则添加单个换行符（复制注释的 GitHub 行为，但不复制呈现的 Markdown 文件）。要求是 .<br>``gfm``true
        sanitize: false,
        smartLists: true,
        smartypants: false,
        xhtml: false
      })
      markdownContent.value = marked(data.download.md)
      break
    default:
      data.download.other = url
      break
  }
  open.value = true
}
const downloadFile = async (fileName, fileType) => {
  const res = await download({
    fileName,
    fileType
  })
  // 创建一个URL链接以供下载或预览
  const url = window.URL.createObjectURL(res)
  // 创建一个隐藏的a标签，模拟下载行为
  const a = document.createElement('a')
  a.href = url
  a.download = `${fileName}.${fileType}`
  document.body.appendChild(a)
  a.click()
  // 下载后移除a标签
  a.remove()
}
const rendered = () => {
  console.log('渲染完成')
}
const errorHandler = () => {
  console.log('渲染失败')
}
</script>

<style lang="scss" scoped>
.center {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  overflow: hidden;
}
.report-content {
  width: 100%;
  display: flex;
  .report-main {
    display: flex;
    justify-content: start;
    flex-wrap: wrap;
    width: 100%;
    .report-item {
      width: 256px;
      height: 161px;
      border: 1px solid #e2e2e2;
      border-radius: 4px;
      padding: 16px;
      margin-left: 50px;
      cursor: pointer;
      .report-title {
        font-size: 17px;
        font-family: AliMedium;
        color: #333;
        overflow: hidden;
        line-height: 24px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        line-clamp: 1;
        -webkit-line-clamp: 1;
        word-break: break-all;
        margin-bottom: 10px;
      }
      .file-type,
      .report-time,
      .report-person {
        font-size: 12px;
        color: #919eab;
        line-height: 28px;
        font-family: AliRegularL3;
      }
      .report-dispose {
        margin-top: 20px;
        display: flex;
        justify-content: space-around;
      }
      &:nth-child(n + 4) {
        margin-top: 24px;
      }
      &:hover {
        //background: linear-gradient(to right bottom, rgba(202,228,255,0.3),rgba(202,228,255,0.1));
        box-shadow:
          0px 5px 9px 0px rgba(0, 59, 141, 0.05),
          0px 7px 27px 0px rgba(0, 56, 134, 0.08),
          0px 0px 3px 0px rgba(0, 59, 141, 0.06);
        .report-title {
          color: #1d78f4;
        }
      }
    }
  }
}
.no-data {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.view-text,
.view-image {
  width: 100%;
  height: 100%;
}
</style>
